package com.android.settings.audio.peq.peq.ui;

import static com.android.settings.audio.peq.peq.ui.SoundEffectPrefabsActivity.DATA_TYPE_EQ;
import static com.android.settings.audio.peq.peq.ui.SoundEffectPrefabsActivity.DATA_TYPE_MSEB;
import static com.android.settings.audio.peq.peq.ui.SoundEffectPrefabsActivity.DATA_TYPE_PEQ;

import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.android.settings.audio.peq.peq.ui.dialog.CommanDialog;
import com.android.settings.R;
import com.android.settings.audio.peq.peq.Coeff;
import com.android.settings.audio.peq.peq.FrequencyResponse;
import com.android.settings.audio.peq.peq.SmartAv;
import com.android.settings.audio.peq.peq.SmartPlayer;
import com.android.settings.audio.peq.peq.filter.FilterManager;
import com.android.settings.audio.peq.peq.filter.FilterType;
import com.android.settings.audio.peq.peq.widget.PEQImportDialog;
import com.android.settings.audio.peq.qr.Constant;
import com.android.settings.audio.peq.qr.QrManager;
import com.android.settings.audio.peq.skin.SkinManager;
import com.android.settings.audio.peq.soundeffect.PluginDataManager;
import com.android.settings.audio.peq.soundeffect.ServerConfigManager;
import com.android.settings.audio.peq.soundeffect.ServerConfigSave;
import com.android.settings.audio.peq.soundeffect.SoundEffectConfig;
import com.android.settings.audio.peq.soundeffect.SoundEffectManager;
import com.android.settings.audio.peq.tools.MmqStateTools;
import com.android.settings.audio.peq.user.Callback;
import com.android.settings.audio.peq.user.UserManager;
import com.android.settings.audio.peq.util.BuildConfig;
import com.android.settings.audio.peq.util.FileUtil;
import com.android.settings.audio.peq.util.GetSize;
import com.android.settings.audio.peq.util.LogPlus;
import com.android.settings.audio.peq.util.NameString;
import com.android.settings.audio.peq.util.NetWorkUtils;
import com.android.settings.audio.peq.util.ShareprefenceTool;
import com.android.settings.audio.peq.util.ToastTool;
import com.android.settings.audio.peq.util.Util;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import io.reactivex.Observable;

public class SoundEffectPrefabsPresenter implements ISoundEffectPrefabsActivityPresenter {
    public SoundEffectPrefabsActivity mActivity;

    public SoundEffectPrefabsPresenter(SoundEffectPrefabsActivity activity) {
        this.mActivity = activity;
    }

    public void init() {

    }

    public void savePeqDataToLocalFile(SoundEffectConfig soundEffectConfig) {
        new Thread(() -> {
            PluginDataManager.PeqData peqData;
            try {
                peqData = getPeqData(soundEffectConfig);
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }

            String savePath = PEQImportDialog.getFileSavePath(mActivity);
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String filePath = savePath + soundEffectConfig.getName() + ".peq";
            try {
                File targetFile = new File(filePath);
                if (targetFile.exists()) {
                    //todo 增加是否覆盖弹框提示
                    mActivity.runOnUiThread(() -> showConfirmOverrideDialog(new OnDialogActionCallback() {
                        @Override
                        public void onConfirm() {
                            String json = new Gson().toJson(peqData);
                            FileUtil.writeBytesToFile(json.getBytes(), filePath);
                            File file = new File(filePath);

                            boolean success = file.exists() && file.length() > 0;
                            if (!success) {
                                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.peq_store_failure));
                                return;
                            }

                            mActivity.runOnUiThread(() -> {
                                String title = mActivity.getResources().getString(R.string.peq_store_successful);
                                PEQImportDialog.showPathMessage(mActivity, title, filePath);
                            });
                        }

                        @Override
                        public void onCancel() {

                        }
                    }));
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            String json = new Gson().toJson(peqData);
            FileUtil.writeBytesToFile(json.getBytes(), filePath);
            file = new File(filePath);

            boolean success = file.exists() && file.length() > 0;
            if (!success) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.peq_store_failure));
                return;
            }

            mActivity.runOnUiThread(() -> {
                String title = mActivity.getResources().getString(R.string.peq_store_successful);
                PEQImportDialog.showPathMessage(mActivity, title, filePath);
            });
        }).start();
    }

    public void deletePeqData(SoundEffectConfig soundEffectConfig) {
        new Thread(() -> {
            //todo 如果存在于服务器则尝试从服务器删除
            if (soundEffectConfig.getServerDataId() != null || soundEffectConfig.isServerConfig()) {
                doDeleteConfigFromServer(soundEffectConfig, new Callback<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject resp) {
                        //继续删除本地的数据
                        //如果本地存在则继续删除本地的数据
                        if (!soundEffectConfig.isServerConfig()) {
                            boolean isRemoved = PluginDataManager.getInstance().deleteData(PluginDataManager.KEY_PEQ, soundEffectConfig.getId());
                        }
                        if (soundEffectConfig.isChecked()) {
                            SoundEffectConfig tempConfig = new SoundEffectConfig(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), false);
                            SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(tempConfig);
                            mActivity.setSelectedSoundEffectConfig(tempConfig);
                            mActivity.setResult(tempConfig);
                        }

                        //令缓存失效
                        if (UserManager.getInstance().currentActiveUser() != null) {
                            ServerConfigManager.getInstance().clearCachedConfigs(UserManager.getInstance().currentActiveUser(), "peq");
                        }

                        mActivity.refreshData();

                        ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_delete_success));
                    }

                    @Override
                    public void onError(Throwable t) {
                        ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_delete_faile));
                        //todo 弹框提示是否将本地删除
                    }
                });
                return;
            }
            //属于本地数据
            boolean isRemoved = PluginDataManager.getInstance().deleteData(PluginDataManager.KEY_PEQ, soundEffectConfig.getId());
            if (isRemoved) {
                if (soundEffectConfig.isChecked()) {
                    SoundEffectConfig tempConfig = new SoundEffectConfig(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), false);
                    SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(tempConfig);
                    mActivity.setSelectedSoundEffectConfig(tempConfig);
                    mActivity.setResult(tempConfig);
                }
                mActivity.refreshData();
            }

            ToastTool.showToast(mActivity.getApplicationContext(), isRemoved ? mActivity.getString(R.string.peq_delete_success) : mActivity.getString(R.string.peq_delete_faile));
        }).start();
    }

    @Override
    public List<SoundEffectPrefabsActivity.ActionPair> getActions(SoundEffectConfig soundEffectConfig) {
        int dataType = mActivity.getDataType();
        final List<SoundEffectPrefabsActivity.ActionPair> actionPairs = new ArrayList<>();
        if (!PluginDataManager.NONE_ID.equals(soundEffectConfig.getId())) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_edit), (action, s) -> {
            //showInfoDialog(s);
            showPluginEditFormDialog(s);
        }));
        if (dataType == DATA_TYPE_PEQ) {
            if (PluginDataManager.NONE_ID.equals(soundEffectConfig.getId())) {
                actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_plg_resume_to_default), (action, s) -> {
                    resumeZeroValuesForPEQ(s);
                }));
            }
            if (!PluginDataManager.NONE_ID.equals(soundEffectConfig.getId())) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_export_to_local), (action, s) -> {
                savePeqDataToLocalFile(s);
            }));
            if (false && !PluginDataManager.NONE_ID.equals(soundEffectConfig.getId()) && !soundEffectConfig.isSystem()) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_cd_share), (action, s) -> {
                createPEQQrcodeAndShow(s);
            }));
            if (!PluginDataManager.NONE_ID.equals(soundEffectConfig.getId()) && !soundEffectConfig.isSystem()) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_delete), (action, s) -> {
                deletePeqData(s);
            }));
            if (false && !PluginDataManager.NONE_ID.equals(soundEffectConfig.getId()) && !soundEffectConfig.isSystem() && !soundEffectConfig.isServerConfig() && soundEffectConfig.getServerDataId() == null) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_save_to_server), (action, s) -> {
                saveToServer("peq", soundEffectConfig);
            }));
        } else if (dataType == DATA_TYPE_EQ) {
            if (PluginDataManager.NONE_ID.equals(soundEffectConfig.getId())) {
                actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_plg_resume_to_default), (action, s) -> {
                    resumeZeroValuesForEQ(s);
                }));
            }
            if (!PluginDataManager.NONE_ID.equals(soundEffectConfig.getId())) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_export_to_local), (action, s) -> {
                saveEqDataToLocalFile(s);
            }));
            if (false && !PluginDataManager.NONE_ID.equals(soundEffectConfig.getId()) && !soundEffectConfig.isSystem()) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_cd_share), (action, s) -> {
                createEqQrcodeAndShow(s);
            }));
            if (!PluginDataManager.NONE_ID.equals(soundEffectConfig.getId()) && !soundEffectConfig.isSystem()) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_delete), (action, s) -> {
                deleteEqData(s);
            }));
            if (false && !PluginDataManager.NONE_ID.equals(soundEffectConfig.getId()) && !soundEffectConfig.isSystem() && !soundEffectConfig.isServerConfig() && soundEffectConfig.getServerDataId() == null) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_save_to_server), (action, s) -> {
                saveToServer("eq", soundEffectConfig);
            }));
        } else if (dataType == DATA_TYPE_MSEB) {
            if (PluginDataManager.NONE_ID.equals(soundEffectConfig.getId())) {
                actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_plg_resume_to_default), (action, s) -> {
                    resumeZeroValuesForMSEB(s);
                }));
            }
            if (!PluginDataManager.NONE_ID.equals(soundEffectConfig.getId()) && !soundEffectConfig.isSystem()) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_export_to_local), (action, s) -> {
                saveMsebDataToLocalFile(s);
            }));
            if (false && !PluginDataManager.NONE_ID.equals(soundEffectConfig.getId()) && !soundEffectConfig.isSystem()) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_cd_share), (action, s) -> {
                createMsebQrcodeAndShow(s);
            }));
            if (!PluginDataManager.NONE_ID.equals(soundEffectConfig.getId()) && !soundEffectConfig.isSystem()) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_delete), (action, s) -> {
                deleteMsebData(s);
            }));
            if (false && !PluginDataManager.NONE_ID.equals(soundEffectConfig.getId()) && !soundEffectConfig.isSystem() && !soundEffectConfig.isServerConfig() && soundEffectConfig.getServerDataId() == null) actionPairs.add(new SoundEffectPrefabsActivity.ActionPair(mActivity.getString(R.string.peq_save_to_server), (action, s) -> {
                saveToServer("mseb", soundEffectConfig);
            }));
        }
        return actionPairs;
    }

    private void resumeZeroValuesForMSEB(SoundEffectConfig s) {
        PluginDataManager.MsebData msebData = new PluginDataManager.MsebData();
        msebData.name = s.getName();
        msebData.range = 3;
        msebData.datalist = new ArrayList<>(10);
        for (int i = 0; i < 10; ++i) {
            msebData.datalist.add(0);
        }
        msebData.result = msebData.datalist;
        PluginDataManager.getInstance().savePluginData(PluginDataManager.KEY_MSEB, new PluginDataManager.PluginData(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), msebData));
        mActivity.refreshData();
    }

    private void resumeZeroValuesForEQ(SoundEffectConfig s) {
        PluginDataManager.getInstance().savePluginData(PluginDataManager.KEY_EQ, new PluginDataManager.PluginData(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), PluginDataManager.getInstance().newNoneEqData()));
        mActivity.refreshData();
    }

    private void resumeZeroValuesForPEQ(SoundEffectConfig s) {
        PluginDataManager.getInstance().savePluginData(PluginDataManager.KEY_PEQ, new PluginDataManager.PluginData(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), PluginDataManager.getInstance().newNonePeqData()));
        mActivity.refreshData();
    }

    private void doDeleteConfigFromServer(SoundEffectConfig config, Callback callback) {
        int dataType = mActivity.getDataType();
        final String type = getTypeForApi(dataType);
        String id = "";
        if (config.isServerConfig()) {
            id = config.getId();
        } else if (config.getServerDataId() != null) {
            id = config.getServerDataId();
        }
        deleteConfigFromServer(type, id, new Callback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject resp) {
                try {
                    if (config.isServerConfig() && resp.getInt("resultCode") != 0) {//仅存在于服务器端的配置则需要接口明确返回删除成功, 如果是本地数据则即使接口返回删除失败,也可以继续删除本地数据
                        ToastTool.showToast(mActivity.getApplicationContext(), resp.getString("result"));
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (null != callback) callback.onSuccess(resp);
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_delete_success));
                //todo 刷新
                if (config.isChecked()) {//如果删除的是已经选中的配置则恢复为 默认
                    SoundEffectConfig tempConfig = new SoundEffectConfig(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), false);
                    if (dataType == DATA_TYPE_PEQ) {
                        SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(tempConfig);
                    } else if (dataType == DATA_TYPE_MSEB) {
                        SoundEffectManager.getInstance().saveSoundEffectConfigAsMSEB(tempConfig);
                    } else if (dataType == DATA_TYPE_EQ) {
                        SoundEffectManager.getInstance().saveSoundEffectConfigAsEQ(tempConfig);
                    }
                    mActivity.setSelectedSoundEffectConfig(tempConfig);
                    mActivity.setResult(tempConfig);
                }
                //将本地的关联数据的关联状态清除
                String serverRecordId = config.getId();
                if (dataType == DATA_TYPE_PEQ) {
                    PluginDataManager.getInstance().clearServerDataId(PluginDataManager.KEY_PEQ, serverRecordId);
                } else if (dataType == DATA_TYPE_MSEB) {
                    PluginDataManager.getInstance().clearServerDataId(PluginDataManager.KEY_MSEB, serverRecordId);
                } else if (dataType == DATA_TYPE_EQ) {
                    PluginDataManager.getInstance().clearServerDataId(PluginDataManager.KEY_EQ, serverRecordId);
                }

                mActivity.refreshData();
            }

            @Override
            public void onError(Throwable t) {
                if (null != callback) callback.onError(t);
                ToastTool.showToast(mActivity.getApplicationContext(), t.getMessage());
            }
        });
    }

    private String getTypeForApi(int dataType) {
        String type = "";
        if (dataType == DATA_TYPE_EQ) {
            type = "eq";
        } else if (dataType == DATA_TYPE_PEQ) {
            type = "peq";
        } else if (dataType == DATA_TYPE_MSEB) {
            type = "mseb";
        }
        return type;
    }

    @Override
    public void deleteConfigFromServer(String type, String id, Callback<JSONObject> callback) {
        if (UserManager.getInstance().currentActiveUser() == null) {
            if (callback != null) callback.onError(new Exception(mActivity.getString(R.string.peq_plg_net_notlogin_details)));
            return;
        }
        boolean isNetworkAvailable = NetWorkUtils.isConnected(mActivity.getApplicationContext());
        if (!isNetworkAvailable) {//网络不可用则暂不提交
            if (callback != null) callback.onError(new Exception("network error"));
            return;
        }
//        String ids = id;
//        UserManager.getInstance().deletePluginConfigs(UserManager.getInstance().currentActiveUser().email(), type, UserManager.getInstance().currentActiveUser().token(), ids).call(new Callback<JSONObject>() {
//            @Override
//            public void onSuccess(JSONObject data) {
//                if (BuildConfig.DEBUG) LogPlus.d("onSuccess: " + data.toString());
//                if (callback != null) callback.onSuccess(data);
//            }
//
//            @Override
//            public void onError(Throwable t) {
//                t.printStackTrace();
//                if (callback != null) callback.onError(t);
//            }
//        });
    }

    @Override
    public List<List<double[]>> getPeqValues(SoundEffectConfig o) throws Exception {
        List<double[]> xValuesList = new ArrayList<>();
        List<double[]> yValuesList = new ArrayList<>();

        //////全部频段(band0-band9)叠加//////
        final int fs = 44100;
        final int n = 400;
        double startF = 20;
        double endF = 20000;
        double logStep = (Math.log10(endF) - Math.log10(startF)) / n;
        double step = Math.pow(10, logStep);

        double[] f = new double[n];
        double[] semilogf = new double[n];
        for (int i = 0; i < n; i++) {
            f[i] = startF * Math.pow(step, i); //按对数划分为n个点
            semilogf[i] = Math.log10(f[i]);  //半对数绘制时，对f取以10为底的对数
        }
        double[] freqResponseAllBandsYValues = new double[n];
        List<PluginDataManager.BandItem> bandItems;
        if (o.isServerConfig()) {
            ServerConfigManager.ServerPeqDataConfig serverPeqDataConfig = PluginDataManager.getInstance().jsonToData(o.getConfigData(), ServerConfigManager.ServerPeqDataConfig.class);
            bandItems = serverPeqDataConfig.getBands();
        } else if (!o.isSystem() && !o.isServerConfig()) {
            //本地配置
            PluginDataManager.PeqData peqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_PEQ, o.getId(), new TypeToken<PluginDataManager.PeqData>() {
            });
            if (peqData == null) {
                peqData = PluginDataManager.getInstance().newNonePeqData();
            }
            bandItems = peqData.bands;
        } else {
            //todo 系统预设
            //属于在线数据 需要下载
            String json = o.getSystemData();
            try {
                if (NetWorkUtils.isConnected(mActivity.getApplicationContext())) {
                    /*Response<ResponseBody> response = getRetrofit().create(ApiInterface.class).downloadFileByCall(o.getDataUrl()).execute();
                    json = response.body().string();*/
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            PluginDataManager.PeqData peqData = PluginDataManager.getInstance().jsonToData(json, PluginDataManager.PeqData.class);
            bandItems = peqData.bands;
        }

        if (bandItems == null) {
            bandItems = new ArrayList<>();
        }

        for (int bandIndex = 0, bandsLen = bandItems.size(); bandIndex < bandsLen; ++bandIndex) {
            PluginDataManager.BandItem band = bandItems.get(bandIndex);
            if (band.on == 0) continue;
            //滤波器
            FilterType filterType = convertFilterType(band.filter);
            Coeff coeff = FilterManager.getInstance().getFilter(filterType).getValue(band.freq, band.q, band.gain, fs);
            if (!Double.isNaN(coeff.getB0()) && !Double.isNaN(coeff.getB1()) && !Double.isNaN(coeff.getB2()) && !Double.isNaN(coeff.getA0()) && !Double.isNaN(coeff.getA1()) && !Double.isNaN(coeff.getA2())) {
                double[] yValues = FrequencyResponse.getFreqzn(coeff, fs, f);
                for (int i = 0, len = yValues.length; i < len; i++) {
                    freqResponseAllBandsYValues[i] += yValues[i];
                }
            }
        }
        //////全部频段(band0-band9)叠加//////

        xValuesList.add(semilogf);
        yValuesList.add(freqResponseAllBandsYValues);
        return new ArrayList<List<double[]>>() {
            {
                add(xValuesList);
                add(yValuesList);
            }
        };
    }

    @Override
    public List<List<double[]>> getMsebValues(SoundEffectConfig o) throws Exception {
        List<double[]> xValuesList = new ArrayList<>();
        List<double[]> yValuesList = new ArrayList<>();

        //////全部频段(band0-band9)叠加//////
        final int fs = 44100;
        final int n = 400;
        double startF = 20;
        double endF = 20000;
        double logStep = (Math.log10(endF) - Math.log10(startF)) / n;
        double step = Math.pow(10, logStep);

        double[] f = new double[n];
        double[] semilogf = new double[n];
        for (int i = 0; i < n; i++) {
            f[i] = startF * Math.pow(step, i); //按对数划分为n个点
            semilogf[i] = Math.log10(f[i]);  //半对数绘制时，对f取以10为底的对数
        }
        double[] freqResponseAllBandsYValues = new double[n];

        List<Integer> datalist = null;
        int dataRange = 0;
        if (o.isServerConfig()) {
            ServerConfigManager.ServerMsebDataConfig serverMsebDataConfig = PluginDataManager.getInstance().jsonToData(o.getConfigData(), ServerConfigManager.ServerMsebDataConfig.class);
            datalist = serverMsebDataConfig.getDatalist();
            dataRange = serverMsebDataConfig.getRange();
        } else if (!o.isSystem()) {
            //本地配置
            PluginDataManager.MsebData msebData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_MSEB, o.getId(), new TypeToken<PluginDataManager.MsebData>() {
            });
            datalist = msebData.datalist;
            dataRange = msebData.range;
        } else {
            //todo 系统预设
            datalist = new ArrayList<>();
            dataRange = 0;
        }
        List<PluginDataManager.BandItem> bandItems = new ArrayList<>();
        for (Integer d : datalist) {
            PluginDataManager.BandItem bandItem = new PluginDataManager.BandItem();
            bandItem.gain = 0.3;
            bandItem.on = 1;
            bandItem.q = 0.2;
            bandItem.freq = 31;
            bandItem.filter = 0;
            bandItems.add(bandItem);
        }
        for (int bandIndex = 0, bandsLen = bandItems.size(); bandIndex < bandsLen; ++bandIndex) {
            PluginDataManager.BandItem band = bandItems.get(bandIndex);
            if (band.on == 0) continue;
            //滤波器
            FilterType filterType = convertFilterType(band.filter);
            Coeff coeff = FilterManager.getInstance().getFilter(filterType).getValue(band.freq, band.q, band.gain, fs);
            if (!Double.isNaN(coeff.getB0()) && !Double.isNaN(coeff.getB1()) && !Double.isNaN(coeff.getB2()) && !Double.isNaN(coeff.getA0()) && !Double.isNaN(coeff.getA1()) && !Double.isNaN(coeff.getA2())) {
                double[] yValues = FrequencyResponse.getFreqzn(coeff, fs, f);
                for (int i = 0, len = yValues.length; i < len; i++) {
                    freqResponseAllBandsYValues[i] += yValues[i];
                }
            }
        }
        //////全部频段(band0-band9)叠加//////

        xValuesList.add(semilogf);
        yValuesList.add(freqResponseAllBandsYValues);
        return new ArrayList<List<double[]>>() {
            {
                add(xValuesList);
                add(yValuesList);
            }
        };
    }

    @Override
    public float[] getEqFs(SoundEffectConfig o) throws Exception {
        float[] fs = null;
        try {
            PluginDataManager.PluginData pluginData;
            if (o.isServerConfig()) {
                //服务器端配置
                if (BuildConfig.DEBUG) LogPlus.d("###configData:" + o.getConfigData());
                ServerConfigManager.ServerEqDataConfig serverEqDataConfig = new Gson().fromJson(o.getConfigData(), ServerConfigManager.ServerEqDataConfig.class);
                fs = serverEqDataConfig.getValue();
            } else {
                //本地配置
                pluginData = (PluginDataManager.getInstance().getPluginData(PluginDataManager.KEY_EQ, o.getId()));
                if (pluginData != null) {
                    if (pluginData.getValue() instanceof ArrayList) {
                        fs = new float[((ArrayList<Double>) pluginData.getValue()).size()];
                        int i = 0;
                        for (Double v : ((ArrayList<Double>) pluginData.getValue())) {
                            fs[i++] = v.floatValue();
                        }
                    } else {
                        PluginDataManager.EqData eqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_EQ, o.getId(), new TypeToken<PluginDataManager.EqData>() {
                        });
                        if (eqData != null) fs = eqData.value;
                    }
                }
            }

            if (fs == null) {
                fs = PluginDataManager.getInstance().newNoneEqData().value;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return fs;
    }

    @Override
    public String download(String dataUrl) throws Exception {
        /*Response<ResponseBody> response = getRetrofit().create(ApiInterface.class).downloadFileByCall(dataUrl).execute();
        String json = response.body().string();
        return json;*/
        return "";
    }

    private FilterType convertFilterType(int filter) {
        switch (filter) {
            case 0:
                return FilterType.LOW_SHELF;
            case 1:
                return FilterType.PEAKING;
            case 2:
                return FilterType.HIGH_SHELF;
        }

        return FilterType.LOW_SHELF;
    }

    private void deleteEqData(SoundEffectConfig soundEffectConfig) {
        //todo 如果存在于服务器则尝试从服务器删除
        if (soundEffectConfig.getServerDataId() != null || soundEffectConfig.isServerConfig()) {
            doDeleteConfigFromServer(soundEffectConfig, new Callback<JSONObject>() {
                @Override
                public void onSuccess(JSONObject resp) {
                    //继续删除本地的数据
                    boolean isSuccess = PluginDataManager.getInstance().deleteData(PluginDataManager.KEY_EQ, soundEffectConfig.getId());
                    //ToastTool.showToast(mActivity.getApplicationContext(), isSuccess ? mActivity.getString(R.string.delete_success) : mActivity.getString(R.string.delete_faile));
                    if (soundEffectConfig.isChecked()) {
                        SoundEffectConfig tempConfig = new SoundEffectConfig(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), false);
                        SoundEffectManager.getInstance().saveSoundEffectConfigAsEQ(tempConfig);

                        mActivity.setSelectedSoundEffectConfig(tempConfig);
                        mActivity.setResult(tempConfig);
                    }

                    //令缓存失效
                    if (UserManager.getInstance().currentActiveUser() != null) {
                        ServerConfigManager.getInstance().clearCachedConfigs(UserManager.getInstance().currentActiveUser(), "eq");
                    }

                    mActivity.refreshData();
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_delete_success)/* isSuccess ? mActivity.getString(R.string.delete_success) : mActivity.getString(R.string.delete_faile)*/);
                }

                @Override
                public void onError(Throwable t) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_delete_faile));
                }
            });
            return;
        }
        boolean isSuccess = PluginDataManager.getInstance().deleteData(PluginDataManager.KEY_EQ, soundEffectConfig.getId());
        ToastTool.showToast(mActivity.getApplicationContext(), isSuccess ? mActivity.getString(R.string.peq_delete_success) : mActivity.getString(R.string.peq_delete_faile));
        if (isSuccess) {
            if (soundEffectConfig.isChecked()) {
                SoundEffectConfig tempConfig = new SoundEffectConfig(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), false);
                SoundEffectManager.getInstance().saveSoundEffectConfigAsEQ(tempConfig);

                mActivity.setSelectedSoundEffectConfig(tempConfig);
                mActivity.setResult(tempConfig);
            }

            mActivity.refreshData();
        }
    }

    private void createEqQrcodeAndShow(SoundEffectConfig s) {
        new Thread(() -> {
            PluginDataManager.EqData eqData = getEqData(s);
            if (eqData == null) {
                ToastTool.showToast(mActivity.getApplicationContext(), "eq data is null");
                return;
            }
            try {
                eqData.name = (s.getName());
                byte[] eqBytes = eqDataToBytes(eqData);
                //QrcodeActivity.start(mActivity, Constant.QR_SCHEMA_V1_EQ, eqBytes, R.drawable.appicon, s.getName(), "EQ");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    private byte[] eqDataToBytes(PluginDataManager.EqData eqData) throws Exception {
        return QrManager.getInstance().getEncoder(Constant.QR_SCHEMA_V1_EQ).toBytes(eqData);
    }

    private void saveEqDataToLocalFile(SoundEffectConfig soundEffectConfig) {
        new Thread(() -> {
            PluginDataManager.EqData eqData = getEqData(soundEffectConfig);
            if (eqData == null) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.peq_store_failure) + " eq data is null");
                return;
            }

            String savePath = getEqFileSavePath(mActivity);
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String filePath = savePath + soundEffectConfig.getName() + ".eq";
            try {
                File targetFile = new File(filePath);
                if (targetFile.exists()) {
                    mActivity.runOnUiThread(() -> showConfirmOverrideDialog(new OnDialogActionCallback() {
                        @Override
                        public void onConfirm() {
                            String json = new Gson().toJson(eqData);
                            FileUtil.writeBytesToFile(json.getBytes(), filePath);
                            File file = new File(filePath);
                            boolean success = file.exists() && file.length() > 0;
                            if (!success) {
                                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.peq_store_failure));
                                return;
                            }

                            mActivity.runOnUiThread(() -> {
                                String title = mActivity.getResources().getString(R.string.peq_store_successful);
                                PEQImportDialog.showPathMessage(mActivity, title, filePath);
                            });
                        }

                        @Override
                        public void onCancel() {

                        }
                    }));
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            String json = new Gson().toJson(eqData);
            FileUtil.writeBytesToFile(json.getBytes(), filePath);
            file = new File(filePath);

            boolean success = file.exists() && file.length() > 0;
            if (!success) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.peq_store_failure));
                return;
            }

            mActivity.runOnUiThread(() -> {
                String title = mActivity.getResources().getString(R.string.peq_store_successful);
                PEQImportDialog.showPathMessage(mActivity, title, filePath);
            });
        }).start();
    }

    private PluginDataManager.EqData getEqData(SoundEffectConfig soundEffectConfig) {
        PluginDataManager.EqData eqData = null;
        if (soundEffectConfig.isServerConfig()) {//从服务器端拉取的配置
            ServerConfigManager.ServerEqDataConfig serverEqDataConfig;
            try {
                serverEqDataConfig = PluginDataManager.getInstance().jsonToData(soundEffectConfig.getConfigData(), ServerConfigManager.ServerEqDataConfig.class);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            eqData = new PluginDataManager.EqData();
            eqData.name = soundEffectConfig.getName();
            try {
                eqData.device = soundEffectConfig.getServerConfigData().getDevice();
                eqData.description = soundEffectConfig.getServerConfigData().getDescription();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                eqData.value = serverEqDataConfig.getValue();
            } catch (Exception e) {
                eqData.value = new float[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
            }
        } else {
            try {
                eqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_EQ, soundEffectConfig.getId(), new TypeToken<PluginDataManager.EqData>() {
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return eqData;
    }

    public static String getEqFileSavePath(Context context) {
        String savePath = context.getExternalFilesDir(null).toString() + File.separator + "EqFile" + File.separator;
        return ShareprefenceTool.getInstance().getStringShareprefence("eq_file_save_path", context, savePath);
    }

    private void deleteMsebData(SoundEffectConfig s) {
        if (s.getServerDataId() != null || s.isServerConfig()) {
            //存在于服务器端
            doDeleteConfigFromServer(s, new Callback() {
                @Override
                public void onSuccess(Object resp) {
                    //继续删除本地的数据
                    boolean isSuccess = false;
                    try {
                        PluginDataManager.getInstance().deleteData(PluginDataManager.KEY_MSEB, s.getId());
                        Util.deleteEqSet(s.getName(), mActivity.getApplicationContext(), 0);
                        String currentValue = ShareprefenceTool.getInstance().getStringShareprefence(MsebSettingActivityPresenter.MSEB_DATA_IS_CHECKED, mActivity.getApplicationContext(), "");
                        if (currentValue.equals(s.getName())) {
                            ShareprefenceTool.getInstance().setStringSharedPreference(MsebSettingActivityPresenter.MSEB_DATA_IS_CHECKED, mActivity.getString(R.string.peq_mseb_none), mActivity.getApplicationContext());
                        }
                        isSuccess = true;
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_delete_success)/*isSuccess ? mActivity.getString(R.string.delete_success) : mActivity.getString(R.string.delete_faile)*/);
                    if (s.isChecked()) {
                        SoundEffectConfig tempConfig = new SoundEffectConfig(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), false);
                        SoundEffectManager.getInstance().saveSoundEffectConfigAsMSEB(tempConfig);
                        mActivity.setSelectedSoundEffectConfig(tempConfig);
                        mActivity.setResult(tempConfig);
                    }

                    //令缓存失效
                    if (UserManager.getInstance().currentActiveUser() != null) {
                        ServerConfigManager.getInstance().clearCachedConfigs(UserManager.getInstance().currentActiveUser(), "mseb");
                    }

                    mActivity.refreshData();
                }

                @Override
                public void onError(Throwable t) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_delete_faile));
                }
            });
            return;
        }

        //仅存在于本地
        boolean isSuccess = false;
        try {
            PluginDataManager.getInstance().deleteData(PluginDataManager.KEY_MSEB, s.getId());
            Util.deleteEqSet(s.getName(), mActivity.getApplicationContext(), 0);
            String currentValue = ShareprefenceTool.getInstance().getStringShareprefence(MsebSettingActivityPresenter.MSEB_DATA_IS_CHECKED, mActivity.getApplicationContext(), "");
            if (currentValue.equals(s.getName())) {
                ShareprefenceTool.getInstance().setStringSharedPreference(MsebSettingActivityPresenter.MSEB_DATA_IS_CHECKED, mActivity.getString(R.string.peq_mseb_none), mActivity.getApplicationContext());
            }
            isSuccess = true;
        } catch (Throwable e) {
            e.printStackTrace();
        }

        ToastTool.showToast(mActivity.getApplicationContext(), isSuccess ? mActivity.getString(R.string.peq_delete_success) : mActivity.getString(R.string.peq_delete_faile));
        if (isSuccess) {
            if (s.isChecked()) {
                SoundEffectConfig tempConfig = new SoundEffectConfig(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), false);
                SoundEffectManager.getInstance().saveSoundEffectConfigAsMSEB(tempConfig);
                mActivity.setSelectedSoundEffectConfig(tempConfig);
                mActivity.setResult(tempConfig);
            }
            mActivity.refreshData();
        }
    }

    private void createMsebQrcodeAndShow(SoundEffectConfig s) {
        new Thread(() -> {
            byte[] bytes = new byte[0];
            try {
                bytes = getMsebDataBytes(s);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //QrcodeActivity.start(mActivity, Constant.QR_SCHEMA_V1_MSEB, bytes, R.drawable.appicon, s.getName(), "MSEB");
        }).start();
    }

    private byte[] getMsebDataBytes(SoundEffectConfig s) throws Exception {
        PluginDataManager.MsebData msebData;
        if (!s.isSystem() && !s.isServerConfig()) {
            //本地数据
            msebData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_MSEB, s.getId(), new TypeToken<PluginDataManager.MsebData>() {
            });
        } else if (s.isServerConfig()) {//从服务器端拉取的配置
            try {
                ServerConfigManager.ServerMsebDataConfig serverMsebDataConfig = PluginDataManager.getInstance().jsonToData(s.getConfigData(), ServerConfigManager.ServerMsebDataConfig.class);

                msebData = new PluginDataManager.MsebData();
                msebData.name = s.getName();
                msebData.device = s.getServerConfigData().getDevice();
                msebData.description = s.getServerConfigData().getDescription();
                msebData.datalist = serverMsebDataConfig.getDatalist();
                msebData.result = msebData.datalist;
            } catch (Exception e) {
                e.printStackTrace();
                msebData = null;
            }
        } else {
            //todo
            String json = s.getSystemData();
            try {
                if (NetWorkUtils.isConnected(mActivity.getApplicationContext())) {
                    //属于在线数据 需要下载
                    /*Response<ResponseBody> response = getRetrofit().create(ApiInterface.class).downloadFileByCall(s.getDataUrl()).execute();
                    json = response.body().string();*/
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            msebData = PluginDataManager.getInstance().jsonToData(json, PluginDataManager.MsebData.class);

        }
        if (msebData != null && TextUtils.isEmpty(msebData.name)) msebData.name = s.getName();
        return QrManager.getInstance().getEncoder(Constant.QR_SCHEMA_V1_MSEB).toBytes(msebData);
    }

    private void saveMsebDataToLocalFile(SoundEffectConfig s) {
        String savePath = "";//EqImportDialog.getFileSavePath(mActivity.getApplicationContext());

        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String filePath = savePath + s.getName() + ".mseb";
        boolean success = false;
        if (s.isSystem()) {
            return;
        }
        List<Integer> datalist = null;
        int range = 0;
        String device = "";
        String description = "";
        if (s.isServerConfig()) {
            try {
                ServerConfigManager.ServerMsebDataConfig serverMsebDataConfig = PluginDataManager.getInstance().jsonToData(s.getConfigData(), ServerConfigManager.ServerMsebDataConfig.class);
                datalist = serverMsebDataConfig.getDatalist();
                range = serverMsebDataConfig.getRange();

                device = s.getServerConfigData().getDevice();
                description = s.getServerConfigData().getDescription();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            PluginDataManager.MsebData msebData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_MSEB, s.getId(), new TypeToken<PluginDataManager.MsebData>() {
            });
            datalist = msebData.datalist;
            range = msebData.range;
            device = msebData.device;
            description = msebData.description;
        }
        try {
            File targetFile = new File(filePath);
            if (targetFile.exists()) {
                //todo 增加是否覆盖弹框提示
                final String finalDevice = device;
                String finalDescription = description;
                int finalRange = range;
                List<Integer> finalDatalist = datalist;
                mActivity.runOnUiThread(() -> showConfirmOverrideDialog(new OnDialogActionCallback() {
                    @Override
                    public void onConfirm() {
                        boolean success = writeMsebToFile(filePath, s, finalDevice, finalDescription, finalRange, finalDatalist);
                        if (!success) {
                            ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.peq_store_failure));
                            return;
                        }

                        String dilogText = mActivity.getResources().getString(R.string.peq_store_successful);
                        mActivity.runOnUiThread(() -> {
                            //EqImportDialog.ShowPathMessage(mActivity, dilogText, filePath)
                        });
                    }

                    @Override
                    public void onCancel() {

                    }
                }));
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        success = writeMsebToFile(filePath, s, device, description, range, datalist);
        if (!success) {
            ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.peq_store_failure));
        } else {
            String dilogText = mActivity.getResources().getString(R.string.peq_store_successful);
            mActivity.runOnUiThread(() -> {
                //EqImportDialog.ShowPathMessage(mActivity, dilogText, filePath)
            });
        }
    }

    private boolean writeMsebToFile(String filePath, SoundEffectConfig s, String device, String description, int range, List<Integer> datalist) {
        try {
            PluginDataManager.MsebData msebData = new PluginDataManager.MsebData();
            msebData.name = s.getName();
            msebData.device = device;
            msebData.description = description;
            msebData.range = range;
            msebData.datalist = datalist;
            msebData.result = datalist;
            byte[] bytes = QrManager.getInstance().getEncoder(Constant.QR_SCHEMA_V1_MSEB).toBytes(msebData);
            FileUtil.writeBytesToFile(bytes, filePath);
            File file = new File(filePath);
            return file.exists() && file.length() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public String getCurrentLanguage() {
        Resources res = mActivity.getResources();
        Configuration config = res.getConfiguration();
        String country = config.locale.getCountry();
        return config.locale.getLanguage() + "-" + country;
    }

    //private Retrofit retrofit;

    //private Retrofit getRetrofit() {
    //    if (retrofit != null) return retrofit;
//        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(s -> {
//            if (false)
//                Log.v("http request", "log: " + s);
//        });
//        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
//
//        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        OkHttpClient client = builder.addInterceptor(logging)
//                .connectTimeout(10, TimeUnit.SECONDS)
//                .readTimeout(10, TimeUnit.SECONDS)
//                .writeTimeout(10, TimeUnit.SECONDS)
//                .sslSocketFactory(SmartPlayer.getInstance().getSSLSocketFactory(), SmartPlayer.getInstance().getX509TrustManager())
//                .hostnameVerifier(new NullHostNameVerifier())
//                .retryOnConnectionFailure(true).build();
//        retrofit = new Retrofit.Builder()
//                .client(client)
//                .baseUrl(DebugConfig.otaServerUrl())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .addConverterFactory(GsonConverterFactory.create(InitUtil.getGsonMapper()))
//                .build();
   //     return retrofit;
    //}

    public void createPEQQrcodeAndShow(SoundEffectConfig soundEffectConfig) {
        new Thread(() -> {
            try {
                byte[] peqData = peqDataToBytes(soundEffectConfig);
                //android.graphics.Bitmap qrBitmap = QrManager.getInstance().createQrcodeByEncoder(Constant.QR_SCHEMA_V1_PEQ, peqData, 300, 300, BitmapFactory.decodeResource(mActivity.getResources(), R.mipmap.appicon2_foreground));
                if (mActivity == null || mActivity.isDestroyed() || mActivity.isFinishing()) {
                    return;
                }
                //QrcodeActivity.start(mActivity, Constant.QR_SCHEMA_V1_PEQ, peqData, R.drawable.appicon, soundEffectConfig.getName(), "PEQ");
            } catch (QrManager.BusinessException e) {
                e.printStackTrace();
                ToastTool.showToast(mActivity.getApplicationContext(), e.getLocalizedMessage());
            } catch (Exception e) {
                e.printStackTrace();
                ToastTool.showToast(mActivity.getApplicationContext(), e.getLocalizedMessage());
            }
        }).start();
    }

    public void doApplyValue(SoundEffectConfig soundEffectConfig) throws Exception {
        switch (mActivity.getDataType()) {
            case DATA_TYPE_EQ:
                doApplyValueForEQ(soundEffectConfig);
                break;
            case DATA_TYPE_MSEB:
                doApplyValueForMSEB(soundEffectConfig);
                break;
            case DATA_TYPE_PEQ:
                doApplyValueForPEQ(soundEffectConfig);
                break;
        }
    }

    private void doApplyValueForPEQ(SoundEffectConfig soundEffectConfig) {
        new Thread(() -> {
            PluginDataManager.PeqData peqData = null;
            if (soundEffectConfig.isSystem()) {
                String json = soundEffectConfig.getSystemData();
                //属于在线数据 需要下载
                if (NetWorkUtils.isConnected(mActivity.getApplicationContext())) {
                    try {
                        /*Response<ResponseBody> response = getRetrofit().create(ApiInterface.class).downloadFileByCall(soundEffectConfig.getDataUrl()).execute();
                        json = response.body().string();*/
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
                try {
                    peqData = PluginDataManager.getInstance().jsonToData(json, PluginDataManager.PeqData.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (soundEffectConfig.isServerConfig()) {
                ServerConfigManager.ServerPeqDataConfig serverPeqDataConfig = null;
                try {
                    serverPeqDataConfig = PluginDataManager.getInstance().jsonToData(soundEffectConfig.getConfigData(), ServerConfigManager.ServerPeqDataConfig.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
                peqData = new PluginDataManager.PeqData();
                peqData.bands = serverPeqDataConfig.getBands();
            } else {
                //本地配置
                peqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_PEQ, soundEffectConfig.getId(), new TypeToken<PluginDataManager.PeqData>() {
                });
            }

            try {
                if (peqData == null) {
                    return;
                }
                //记录开关状态
                ShareprefenceTool.getInstance().setBooleanSharedPreference(PEQActivity.PEQ_ISOPEN, true, mActivity);

                if (BuildConfig.DEBUG) LogPlus.d("peqData:" + peqData);
                //使能PEQ
                SmartAv.getInstance().native_setPeqValueEnable(1/*是否打开 1.打开 0:关闭*/);
                SmartAv.getInstance().native_setPeqValuePreAmp((float) peqData.pre_amp);
                SmartAv.getInstance().native_setPeqValuePreAmpEnable(1/*是否打开 1.打开 0:关闭*/);

                int index = 0;
                for (PluginDataManager.BandItem band : peqData.bands) {
                    SmartAv.getInstance().native_setPeqValueItem(index++, band.on, (float) band.freq, (float) band.q, (float) band.gain, band.filter);
                }

                // 如果当前歌曲不支持调音则进行提示
                boolean isMmqPlaying = MmqStateTools.getInstance().currentMusicIsMMq();
                if (isMmqPlaying) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.mmq_state_try_agin_next));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }).start();
    }

    private void doApplyValueForMSEB(SoundEffectConfig soundEffectConfig) {
        new Thread(() -> {
            List<Integer> datalist = null;
            if (soundEffectConfig.isSystem()) {
                //系统预设, 属于在线数据 需要下载
                try {
                    String json = soundEffectConfig.getSystemData();
                    try {
                        if (NetWorkUtils.isConnected(mActivity.getApplicationContext())) {
                            /*Response<ResponseBody> response = getRetrofit().create(ApiInterface.class).downloadFileByCall(soundEffectConfig.getDataUrl()).execute();
                            json = response.body().string();*/
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    JSONObject jsonObject = new JSONObject(json);
                    String name = jsonObject.getString("name");
                    JSONArray result = jsonObject.getJSONArray("result");
                    int range = jsonObject.getInt("range");
                    datalist = new ArrayList<>();
                    for (int i = 0; i < result.length(); i++) {
                        datalist.add(result.getInt(i));
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            } else if (soundEffectConfig.isServerConfig()) {
                ServerConfigManager.ServerMsebDataConfig serverMsebDataConfig = null;
                try {
                    serverMsebDataConfig = PluginDataManager.getInstance().jsonToData(soundEffectConfig.getConfigData(), ServerConfigManager.ServerMsebDataConfig.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
                datalist = serverMsebDataConfig.getDatalist();
            } else {
                //本地配置
                PluginDataManager.MsebData msebData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_MSEB, soundEffectConfig.getId(), new TypeToken<PluginDataManager.MsebData>() {
                });
                if (msebData != null) {
                    datalist = msebData.datalist;
                }
            }

            final String[] Key = {"mseb_master_temp", "mseb_bass0", "mseb_bass1", "mseb_thickness", "mseb_vocal", "mseb_female", "mseb_male_vocal", "mseb_female_vocal", "mseb_instruments", "mseb_air",};
            if (datalist == null) {
                datalist = new ArrayList<>();
                for (int i = 0, n = Key.length; i < n; i++) {
                    datalist.add(0);
                }
            }
            if (datalist.size() != Key.length) {
                return;
            }
            //使能mseb
            //MediaPlayer.getInstance().enableMseb(true);
            ShareprefenceTool.getInstance().setBooleanSharedPreference(MsebSettingActivityPresenter.SLIDING_EQ, true, mActivity);

            /*for (int i = 0, n = datalist.size(); i < n; ++i) {
                MediaPlayer.getInstance().setMSebData(Key[i], datalist.get(i));
            }*/
            // 如果当前歌曲不支持调音则进行提示
            boolean isMmqPlaying = MmqStateTools.getInstance().currentMusicIsMMq();
            if (isMmqPlaying) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.mmq_state_try_agin_next));
            }
        }).start();
    }

    private void doApplyValueForEQ(SoundEffectConfig soundEffectConfig) {
        new Thread(() -> {
            //使能eq
            SmartPlayer.getInstance().setEqEnable(true);
            //ShareprefenceTool.getInstance().setBooleanSharedPreference(EqActivity.EQ_ISOPEN, true, mActivity);
            if (soundEffectConfig.isSystem()) {
                final Map<String, float[]> eqPointsForSystem = new HashMap<>();
//                eqPointsForSystem.put(NameString.getResoucesString(mActivity, R.string.equalizer_blues), EqActivity.blues);
//                eqPointsForSystem.put(NameString.getResoucesString(mActivity, R.string.equalizer_classic), EqActivity.classic);
//                eqPointsForSystem.put(NameString.getResoucesString(mActivity, R.string.equalizer_dance), EqActivity.dance);
//                eqPointsForSystem.put(NameString.getResoucesString(mActivity, R.string.equalizer_jazz), EqActivity.jazz);
//                eqPointsForSystem.put(NameString.getResoucesString(mActivity, R.string.equalizer_metal), EqActivity.metal);
//                eqPointsForSystem.put(NameString.getResoucesString(mActivity, R.string.equalizer_pop), EqActivity.pop);
//                eqPointsForSystem.put(NameString.getResoucesString(mActivity, R.string.equalizer_rock), EqActivity.rock);
//                eqPointsForSystem.put(NameString.getResoucesString(mActivity, R.string.equalizer_voice), EqActivity.voice);
                float[] fs = eqPointsForSystem.get(soundEffectConfig.getName());
                SmartPlayer.getInstance().setEqualizerGain("preset", fs);
                // 如果当前歌曲不支持调音则进行提示
                boolean isMmqPlaying = MmqStateTools.getInstance().currentMusicIsMMq();
                if (isMmqPlaying) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.mmq_state_try_agin_next));
                }
            } else if (soundEffectConfig.isServerConfig()) {
                ServerConfigManager.ServerEqDataConfig serverEqDataConfig = null;
                try {
                    serverEqDataConfig = PluginDataManager.getInstance().jsonToData(soundEffectConfig.getConfigData(), ServerConfigManager.ServerEqDataConfig.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
                float[] fs = serverEqDataConfig.getValue();
                if (fs == null) {
                    //throw new Exception("fs is null");
                    fs = PluginDataManager.getInstance().newNoneEqData().value;
                }
                SmartPlayer.getInstance().setEqualizerGain("crruntent", fs);
                // 如果当前歌曲不支持调音则进行提示
                boolean isMmqPlaying = MmqStateTools.getInstance().currentMusicIsMMq();
                if (isMmqPlaying) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.mmq_state_try_agin_next));
                }
            } else {
                PluginDataManager.EqData eqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_EQ, soundEffectConfig.getId(), new TypeToken<PluginDataManager.EqData>() {
                });
                float[] fs = null;
                if (eqData != null) {
                    fs = eqData.value;
                }
                if (fs == null) {
                    fs = PluginDataManager.getInstance().newNoneEqData().value;
                }
                SmartPlayer.getInstance().setEqualizerGain("crruntent", fs);

                // 如果当前歌曲不支持调音则进行提示
                boolean isMmqPlaying = MmqStateTools.getInstance().currentMusicIsMMq();
                if (isMmqPlaying) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.mmq_state_try_agin_next));
                }
            }
        }).start();
    }

    public interface ApiInterface {
//        @POST("/app/msebSetting/findMsebSettingList")
//        @FormUrlEncoded
//        Observable<ResponseBody> getDataList(@Field("languageCode") String languageCode,
//                                             @Field("productName") String productName,
//                                             @Field("type") String type);
//
//        @POST("/app/msebSetting/findMsebSettingList")
//        @FormUrlEncoded
//        Call<ResponseBody> getDataListByCall(@Field("languageCode") String languageCode,
//                                             @Field("productName") String productName,
//                                             @Field("type") String type
//        );
//
//
//        @GET
//        Observable<ResponseBody> downloadFile(@Url String url);
//
//        @GET
//        Call<ResponseBody> downloadFileByCall(@Url String url);
    }

    private byte[] peqDataToBytes(SoundEffectConfig soundEffectConfig) throws Exception {
        PluginDataManager.PeqData peqData;
        try {
            peqData = getPeqData(soundEffectConfig);
        } catch (Exception e) {
            throw e;
        }
        QrManager.AbsEncoder encoder = QrManager.getInstance().getEncoder(Constant.QR_SCHEMA_V1_PEQ);
        if (encoder == null) {
            throw new NullPointerException("encoder is null");
        }
        return encoder.toBytes(peqData);
    }

    private PluginDataManager.PeqData getPeqData(SoundEffectConfig soundEffectConfig) throws Exception {
        PluginDataManager.PeqData peqData;
        if (!soundEffectConfig.isSystem() && !soundEffectConfig.isServerConfig()) {
            //本地数据
            peqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_PEQ, soundEffectConfig.getId(), new TypeToken<PluginDataManager.PeqData>() {
            });
        } else if (soundEffectConfig.isServerConfig()) {//从服务器端拉取的配置
            try {
                ServerConfigManager.ServerPeqDataConfig serverPeqDataConfig = PluginDataManager.getInstance().jsonToData(soundEffectConfig.getConfigData(), ServerConfigManager.ServerPeqDataConfig.class);

                peqData = new PluginDataManager.PeqData();
                peqData.bands = serverPeqDataConfig.getBands();
                peqData.pre_amp = serverPeqDataConfig.getPre_amp();
                peqData.name = soundEffectConfig.getName();
                peqData.device = soundEffectConfig.getServerConfigData().getDevice();
                peqData.description = soundEffectConfig.getServerConfigData().getDescription();
            } catch (Exception e) {
                e.printStackTrace();
                peqData = null;
            }
        } else {
            //todo
            //属于在线数据 需要下载
            String json = soundEffectConfig.getSystemData();
            try {
                if (NetWorkUtils.isConnected(mActivity.getApplicationContext())) {
                    /*Response<ResponseBody> response = getRetrofit().create(ApiInterface.class).downloadFileByCall(soundEffectConfig.getDataUrl()).execute();
                    json = response.body().string();*/
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }

            peqData = PluginDataManager.getInstance().jsonToData(json, PluginDataManager.PeqData.class);
        }
        if (peqData != null && TextUtils.isEmpty(peqData.name)) peqData.name = soundEffectConfig.getName();
        return peqData;
    }

    private void saveToServer(String type, SoundEffectConfig soundEffectConfig) {
        ////////////////////////////////同步保存到服务器////////////////////////////////
        if (UserManager.getInstance().currentActiveUser() == null) {
            ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_plg_net_notlogin_details));
            return;
        }
        boolean isNetworkAvailable = NetWorkUtils.isConnected(mActivity.getApplicationContext());
        if (!isNetworkAvailable) {//网络不可用
            ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_error_no_network));
            return;
        }
        String device;
        String description;
        Object dataItem;
        if ("eq".equals(type)) {
            PluginDataManager.PluginDataItem eqDataItem = PluginDataManager.getInstance().getDataItem(PluginDataManager.KEY_EQ, soundEffectConfig.getId());
            device = eqDataItem.getDevice();
            description = eqDataItem.getDescription();
            dataItem = eqDataItem;
        } else if ("mseb".equals(type)) {
            PluginDataManager.PluginDataItem msebDataItem = PluginDataManager.getInstance().getDataItem(PluginDataManager.KEY_MSEB, soundEffectConfig.getId());
            device = msebDataItem.getDevice();
            description = msebDataItem.getDescription();
            dataItem = msebDataItem;
        } else if ("peq".equals(type)) {
            PluginDataManager.PluginDataItem peqDataItem = PluginDataManager.getInstance().getDataItem(PluginDataManager.KEY_PEQ, soundEffectConfig.getId());
            device = peqDataItem.getDevice();
            description = peqDataItem.getDescription();
            dataItem = peqDataItem;
        } else {
            throw new RuntimeException("unknown type:" + type);
        }
        Object configs = ServerConfigManager.getInstance().getConfigs(type, soundEffectConfig.getName(), device, "", description, soundEffectConfig);

        final Object sourceDataItem = dataItem;
        ServerConfigManager.getInstance().savePluginConfigToServer(type, configs, new Callback<String>() {
            @Override
            public void onSuccess(String resp) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_data_submission_successful));
                //todo 记录服务器端id 与本地数据关联(标识是否已保存到服务器)
                ServerConfigSave serverConfigSave = null;
                try {
                    serverConfigSave = PluginDataManager.getInstance().jsonToData(resp, ServerConfigSave.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String serverRecordId = null;
                if (serverConfigSave != null && serverConfigSave.getList() != null && !serverConfigSave.getList().isEmpty()) {
                    Long id = serverConfigSave.getList().get(0).getId();
                    if (id != null) {
                        serverRecordId = id + "";
                    }
                }

                ((PluginDataManager.PluginDataItem) sourceDataItem).setServerDataId(serverRecordId);
                mActivity.refreshData();
            }

            @Override
            public void onError(Throwable t) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_data_submission_failed) + t.getLocalizedMessage());
            }
        });
    }


    public void showInfoDialog(SoundEffectConfig soundEffectConfig) {
        Resources mResources = mActivity.getResources();
        if (mResources == null)
            return;
        CommanDialog commanDialog = new CommanDialog(mActivity, R.style.peqMyDialogStyle, CommanDialog.STYLE_POP_NOTITLE_NOBUTTON);
        commanDialog.setCanceledOnTouchOutside(true);
        //commanDialog.addBottomViewNoAdjustView(R.layout.dialog_info_layout_3);
        TextView titleTextView = commanDialog.titleTextView;
        titleTextView.setText(NameString.getResoucesString(mActivity, R.string.peq_songinformation));

        titleTextView.setContentDescription(titleTextView.getText() + "," + NameString.getResoucesString(mActivity, R.string.peq_cd_click_to_close_dialog));
        titleTextView.setOnClickListener(v -> commanDialog.dismiss());
        TextView tvName = commanDialog.findViewById(R.id.tv_name);
        TextView tvDevice = null;//commanDialog.findViewById(R.id.tv_device);
        TextView tvDesc = null;//commanDialog.findViewById(R.id.tv_description);

        String name = soundEffectConfig.getName();
        String device = "";
        String description = "";
        if (!soundEffectConfig.isSystem() && !soundEffectConfig.isServerConfig()) {
            //本地
            switch (mActivity.getDataType()) {
                case DATA_TYPE_EQ:
                    PluginDataManager.EqData eqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_EQ, soundEffectConfig.getId(), new TypeToken<PluginDataManager.EqData>() {
                    });
                    device = eqData.device;
                    description = eqData.description;
                    break;
                case DATA_TYPE_MSEB:
                    PluginDataManager.MsebData msebData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_MSEB, soundEffectConfig.getId(), new TypeToken<PluginDataManager.MsebData>() {
                    });
                    device = msebData.device;
                    description = msebData.description;
                    break;
                case DATA_TYPE_PEQ:
                    PluginDataManager.PeqData peqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_PEQ, soundEffectConfig.getId(), new TypeToken<PluginDataManager.PeqData>() {
                    });
                    device = peqData.device;
                    description = peqData.description;
                    break;
            }
        } else if (soundEffectConfig.isServerConfig()) {
            if (soundEffectConfig.getServerConfigData() != null) {
                device = soundEffectConfig.getServerConfigData().getDevice();
                description = soundEffectConfig.getServerConfigData().getDescription();
            }
        }
        tvName.setText(name);
        tvDevice.setText(device);
        tvDesc.setText(description);
        commanDialog.show();
    }

    /**
     * 编辑已存在的数据(本地数据,位于服务器的数据)
     *
     * @param targetSoundEffectConfig
     */
    public void showPluginEditFormDialog(SoundEffectConfig targetSoundEffectConfig) {
        if (mActivity == null || mActivity.isFinishing() || mActivity.isDestroyed()) return;
        if (null == targetSoundEffectConfig) {
            //throw new RuntimeException("targetSoundEffectConfig must not be null");
            ToastTool.showToast(mActivity.getApplicationContext(), "targetSoundEffectConfig must not be null");
            return;
        }

        Object data = null;
        if (!targetSoundEffectConfig.isSystem() && !targetSoundEffectConfig.isServerConfig()) {
            /*本地配置*/
            TypeToken<?> typeToken = null;
            if (mActivity.getDataType() == DATA_TYPE_EQ) {
                typeToken = new TypeToken<PluginDataManager.EqData>() {
                };
            } else if (mActivity.getDataType() == DATA_TYPE_PEQ) {
                typeToken = new TypeToken<PluginDataManager.PeqData>() {
                };
            } else if (mActivity.getDataType() == DATA_TYPE_MSEB) {
                typeToken = new TypeToken<PluginDataManager.MsebData>() {
                };
            }
            data = PluginDataManager.getInstance().getPluginDataValue(convertDataTypeKey(), targetSoundEffectConfig.getId(), typeToken);
        } else if (targetSoundEffectConfig.isSystem()) {
            /*系统配置*/
            ToastTool.showToast(mActivity.getApplicationContext(), "system");
            return;
        } else if (targetSoundEffectConfig.isServerConfig()) {
            if (mActivity.getDataType() == DATA_TYPE_EQ) {
                try {
                    ServerConfigManager.ServerEqDataConfig eqDataConfig = PluginDataManager.getInstance().jsonToData(targetSoundEffectConfig.getConfigData(), ServerConfigManager.ServerEqDataConfig.class);
                    PluginDataManager.EqData msebData = new PluginDataManager.EqData();
                    msebData.name = targetSoundEffectConfig.getName();
                    msebData.description = targetSoundEffectConfig.getServerConfigData().getDescription();
                    msebData.device = targetSoundEffectConfig.getServerConfigData().getDevice();
                    msebData.value = eqDataConfig.getValue();
                    data = msebData;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (mActivity.getDataType() == DATA_TYPE_PEQ) {
                try {
                    ServerConfigManager.ServerPeqDataConfig serverPeqDataConfig = PluginDataManager.getInstance().jsonToData(targetSoundEffectConfig.getConfigData(), ServerConfigManager.ServerPeqDataConfig.class);
                    PluginDataManager.PeqData peqData = new PluginDataManager.PeqData();
                    peqData.name = targetSoundEffectConfig.getName();
                    peqData.description = targetSoundEffectConfig.getServerConfigData().getDescription();
                    peqData.device = targetSoundEffectConfig.getServerConfigData().getDevice();
                    peqData.bands = serverPeqDataConfig.getBands();
                    peqData.pre_amp = serverPeqDataConfig.getPre_amp();
                    data = peqData;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (mActivity.getDataType() == DATA_TYPE_MSEB) {
                try {
                    ServerConfigManager.ServerMsebDataConfig serverMsebDataConfig = PluginDataManager.getInstance().jsonToData(targetSoundEffectConfig.getConfigData(), ServerConfigManager.ServerMsebDataConfig.class);
                    PluginDataManager.MsebData msebData = new PluginDataManager.MsebData();
                    msebData.name = targetSoundEffectConfig.getName();
                    msebData.description = targetSoundEffectConfig.getServerConfigData().getDescription();
                    msebData.device = targetSoundEffectConfig.getServerConfigData().getDevice();
                    msebData.range = serverMsebDataConfig.getRange();
                    msebData.datalist = serverMsebDataConfig.getDatalist();
                    msebData.result = msebData.datalist;
                    data = msebData;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (data == null) {
            //throw new RuntimeException("data must not be null");
            ToastTool.showToast(mActivity.getApplicationContext(), "data must not be null");
            return;
        }
        Context mContext = mActivity;
        Dialog formDialog = new Dialog(mContext, R.style.peqLogSendDialogStyle);
        formDialog.setCanceledOnTouchOutside(false);
        formDialog.setContentView(R.layout.peq_plugin_config_form_dialog);
        EditText etName = formDialog.findViewById(R.id.et_name);
        PluginDataManager.PluginDataItem targetPeqDataItem = null;
        etName.setText(targetSoundEffectConfig.getName());
        TextView tvFormTitle = formDialog.findViewById(R.id.tv_form_title);
        tvFormTitle.setText(mActivity.getString(R.string.peq_edit));

        targetPeqDataItem = PluginDataManager.getInstance().getDataItem(PluginDataManager.KEY_PEQ, targetSoundEffectConfig.getId());
        EditText etHeadphone = formDialog.findViewById(R.id.et_headphone);
        EditText etDesc = formDialog.findViewById(R.id.et_desc);
        TextView tvDescTitle = formDialog.findViewById(R.id.tv_desc);
        final int maxDescLength = 50;
        tvDescTitle.setText(mActivity.getString(R.string.peq_plg_config_desc_title, (etDesc.getText().length() + "/" + maxDescLength)));
        etDesc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvDescTitle.setText(mActivity.getString(R.string.peq_plg_config_desc_title, (etDesc.getText().length() + "/" + maxDescLength)));
            }
        });

        if (targetPeqDataItem != null) {
            etHeadphone.setText(targetPeqDataItem.getDevice());
            etDesc.setText(targetPeqDataItem.getDescription());
        }
        PluginDataManager.BaseData targetData = null;
        if (BuildConfig.DEBUG) LogPlus.d("data:" + data);
        if (data instanceof PluginDataManager.BaseData) {
            PluginDataManager.BaseData baseData = (PluginDataManager.BaseData) data;
            etName.setText(baseData.name);
            etHeadphone.setText(baseData.device);
            etDesc.setText(baseData.description);
            targetData = baseData;
        }
        if (targetData == null) {
            ToastTool.showToast(mActivity.getApplicationContext(), "targetData must not be null");
            return;
        }
        CheckBox cbSaveToServer = formDialog.findViewById(R.id.cbSaveToServer);
        final String persistsKey = "soundConfigSaveToServer";

        formDialog.findViewById(R.id.container_checkbox).setVisibility(View.GONE);
        formDialog.findViewById(R.id.container_checkbox).setOnClickListener(v -> cbSaveToServer.setChecked(!cbSaveToServer.isChecked()));

        //todo 如果配置数据仅存在于服务器端则属于修改服务器端的配置, 默认勾选保存到服务器, 不可修改为"不保存到服务器"
        final boolean isOnCloudOnly = targetSoundEffectConfig.isServerConfig();
        if (isOnCloudOnly) {
            cbSaveToServer.setChecked(true);
            cbSaveToServer.setEnabled(false);
            formDialog.findViewById(R.id.container_checkbox).setEnabled(false);
        } else {
            final boolean isChecked = ShareprefenceTool.getInstance().getBooleanShareprefence(persistsKey, mActivity.getApplicationContext(), false);
            cbSaveToServer.setChecked(isChecked);
            cbSaveToServer.setOnCheckedChangeListener((buttonView, isChecked1) -> ShareprefenceTool.getInstance().setBooleanSharedPreference(persistsKey, isChecked1, mActivity.getApplicationContext()));
        }

        final boolean isChecked = ShareprefenceTool.getInstance().getBooleanShareprefence(persistsKey, mActivity.getApplicationContext(), /*true*/false);
        cbSaveToServer.setChecked(isChecked);

        Button btn_cancel = formDialog.findViewById(R.id.btn_cancel);
        Button btn_send = formDialog.findViewById(R.id.btn_send);
        formDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        SkinManager.get().changeCustomView(btn_cancel, true);
        SkinManager.get().changeCustomView(btn_send, true);
        SkinManager.get().setCheckBoxButton(cbSaveToServer, R.drawable.peq_skin_selector_checkbox_circle_3);
        PluginDataManager.BaseData finalTargetData = targetData;
        btn_send.setOnClickListener(v -> {
            if (TextUtils.isEmpty(etName.getText())) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_name_required));
                return;
            }
            if (etName.getText().length() > 30) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_name_length_1_10));
                return;
            }
            if (false && TextUtils.isEmpty(etHeadphone.getText())) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_device_required));
                return;
            }
            if (false && TextUtils.isEmpty(etDesc.getText())) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_description_required));
                return;
            }
            if (etDesc.getText().length() > maxDescLength) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_description_required_0) + maxDescLength);
                return;
            }
            if (cbSaveToServer.isChecked()) {
                if (UserManager.getInstance().currentActiveUser() == null) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_plg_net_notlogin_details));
                    return;
                }
                boolean isNetworkAvailable = NetWorkUtils.isConnected(mActivity.getApplicationContext());
                if (!isNetworkAvailable) {//网络不可用
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_error_no_network));
                    return;
                }
            }
            //todo
            String name = etName.getText().toString();
            String device = etHeadphone.getText().toString();
            String desc = etDesc.getText().toString();

            finalTargetData.name = name;
            finalTargetData.device = device;
            finalTargetData.description = desc;

            targetSoundEffectConfig.setName(name);

            PluginDataManager.PluginDataItem dataItem;

            //todo 更新
            try {
                dataItem = new PluginDataManager.PluginDataItem();
                dataItem.setId(targetSoundEffectConfig.getId());
                dataItem.setName(name);
                dataItem.setDevice(device);
                dataItem.setDescription(desc);
                dataItem.setPluginData(new PluginDataManager.PluginData(dataItem.getId(), name, finalTargetData));

                if (isOnCloudOnly) {
                    //todo 更新服务器端配置数据
                    //ToastTool.showToast(mActivity.getApplicationContext(), "更新服务器端配置数据");
                } else {
                    String key = convertDataTypeKey();
                    boolean isUpdated = PluginDataManager.getInstance().updateDataItem(key, dataItem);
                    if (!isUpdated) {
                        ToastTool.showToast(mActivity.getApplicationContext(), "update filed");
                        return;
                    }

                    if (targetSoundEffectConfig.isChecked()) {
                        //修改已保存的数据
                        if (mActivity.getDataType() == DATA_TYPE_PEQ) SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(targetSoundEffectConfig);
                        else if (mActivity.getDataType() == DATA_TYPE_EQ) SoundEffectManager.getInstance().saveSoundEffectConfigAsEQ(targetSoundEffectConfig);
                        else if (mActivity.getDataType() == DATA_TYPE_MSEB) SoundEffectManager.getInstance().saveSoundEffectConfigAsMSEB(targetSoundEffectConfig);
                    }

                    mActivity.refreshData();
                }
            } catch (Exception e) {
                ToastTool.showToast(mActivity, e.getLocalizedMessage());
                return;
            }
            ////////////////////////////////同步保存到服务器////////////////////////////////
            if (cbSaveToServer.isChecked()) {
                if (UserManager.getInstance().currentActiveUser() == null) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_plg_net_notlogin_details));
                    return;
                }
                boolean isNetworkAvailable = NetWorkUtils.isConnected(mActivity.getApplicationContext());
                if (!isNetworkAvailable) {//网络不可用
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_error_no_network));
                    return;
                }
                doSaveToServer(convertDataType(mActivity.getDataType()), targetSoundEffectConfig, dataItem);
            }
            ////////////////////////////////同步保存到服务器////////////////////////////////

            formDialog.dismiss();
        });
        btn_cancel.setOnClickListener(v -> formDialog.dismiss());
        formDialog.show();
    }

    private void doSaveToServer(String type, SoundEffectConfig soundEffectConfig, PluginDataManager.PluginDataItem dataItem) {
        boolean saveToServer = true;
        ////////////////////////////////同步保存到服务器////////////////////////////////
        if (saveToServer) {
            if (UserManager.getInstance().currentActiveUser() == null) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_plg_net_notlogin_details));
                return;
            }
            boolean isNetworkAvailable = NetWorkUtils.isConnected(mActivity.getApplicationContext());
            if (!isNetworkAvailable) {//网络不可用
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_error_no_network));
                return;
            }

            Object configs = ServerConfigManager.getInstance().getConfigs(type, soundEffectConfig.getName(), dataItem.getDevice(), "", dataItem.getDescription(), soundEffectConfig);

            final PluginDataManager.PluginDataItem sourceDataItem = dataItem;
            ServerConfigManager.getInstance().savePluginConfigToServer(type, configs, new Callback<String>() {
                @Override
                public void onSuccess(String resp) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_data_submission_successful));
                    //todo 记录服务器端id 与本地数据关联(标识是否已保存到服务器)
                    ServerConfigSave serverConfigSave = null;
                    try {
                        serverConfigSave = PluginDataManager.getInstance().jsonToData(resp, ServerConfigSave.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String serverRecordId = null;
                    if (serverConfigSave != null && serverConfigSave.getList() != null && !serverConfigSave.getList().isEmpty()) {
                        Long id = serverConfigSave.getList().get(0).getId();
                        if (id != null) {
                            serverRecordId = id + "";
                        }
                    }

                    sourceDataItem.setServerDataId(serverRecordId);

                    if ("peq".equals(type)) {
                        PluginDataManager.getInstance().updateDataItem(PluginDataManager.KEY_PEQ, sourceDataItem);
                    } else if ("mseb".equals(type)) {
                        PluginDataManager.getInstance().updateDataItem(PluginDataManager.KEY_MSEB, sourceDataItem);
                    } else if ("eq".equals(type)) {
                        PluginDataManager.getInstance().updateDataItem(PluginDataManager.KEY_EQ, sourceDataItem);
                    }
                    //令缓存失效
                    ServerConfigManager.getInstance().clearCachedConfigs(UserManager.getInstance().currentActiveUser(), convertDataType(mActivity.getDataType()));

                    mActivity.refreshData();
                }

                @Override
                public void onError(Throwable t) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_data_submission_failed) + t.getLocalizedMessage());
                }
            });
        }
    }

    public static String convertDataType(int dataType) {
        if (dataType == DATA_TYPE_MSEB) {
            return "mseb";
        }
        if (dataType == DATA_TYPE_EQ) {
            return "eq";
        }
        if (dataType == DATA_TYPE_PEQ) {
            return "peq";
        }
        return "";
    }

    public String convertDataTypeKey() {
        if (mActivity.getDataType() == DATA_TYPE_MSEB) {
            return PluginDataManager.KEY_MSEB;
        }
        if (mActivity.getDataType() == DATA_TYPE_EQ) {
            return PluginDataManager.KEY_EQ;
        }
        if (mActivity.getDataType() == DATA_TYPE_PEQ) {
            return PluginDataManager.KEY_PEQ;
        }
        return "";
    }

    private void showConfirmOverrideDialog(OnDialogActionCallback onDialogActionCallback) {
        if (mActivity == null || mActivity.isDestroyed() || mActivity.isFinishing()) {
            return;
        }
        final CommanDialog tipDialog = new CommanDialog(mActivity, R.style.peqMyDialogStyle, CommanDialog.STYLE_3_HASTITLE_HASTWOBUTTON);
        tipDialog.setCanceledOnTouchOutside(true);
        tipDialog.titleTextView.setText(NameString.getResoucesString(mActivity, R.string.peq_tips));
        TextView pathText = new TextView(mActivity);
        pathText.setText(NameString.getResoucesString(mActivity, R.string.peq_file_already_exists_whether_overwrite));
        int padding = GetSize.dip2px(mActivity, 10);
        pathText.setPadding(padding, padding, padding, padding);
        pathText.setSingleLine(false);
        pathText.setTextSize(15);
        pathText.setTextColor(Color.GRAY);
        tipDialog.addView(pathText);
        tipDialog.ok.setOnClickListener(view -> {
            if (onDialogActionCallback != null) onDialogActionCallback.onConfirm();
            tipDialog.dismiss();
        });
        tipDialog.cancle.setOnClickListener(view -> {
            if (onDialogActionCallback != null) onDialogActionCallback.onCancel();
            tipDialog.dismiss();
        });
        tipDialog.show();
    }

    private interface OnDialogActionCallback {
        void onConfirm();

        void onCancel();
    }

    public static class MsebSettingActivityPresenter{
        public static final String MSEB_DATA_IS_CHECKED = "MSEB_DATA_IS_CHECKED";
        public static final String SLIDING_EQ = "SLIDING_EQ";
    }
}
